// Copyright (c) Microsoft Corporation. All rights reserved.
using System.Diagnostics;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Microsoft.Tools.CodeRunner.UnitTest
{
	[TestClass]
	public class RemoteEnvironmentTests 
	{
		private static TestContext context;

		public RemoteEnvironmentTests() 
		{
		}

		[ClassInitialize()]
		public static void ClassInit(TestContext context)
		{
			RemoteEnvironmentTests.context = context;
		}

		[DeploymentItem(@"UnitTest\PipeServer\PipeServer.exe")]
		[DeploymentItem(@"UnitTest\PipeClient\PipeClient.exe")]
		[TestMethod]
		public void TestPipeClientServer()
		{
            EventWaitHandle serverStartedEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "CodeRunner.Test.ServerStarted.Event");

		    Process procServer = Process.Start("PipeServer.exe");
			
			// Wait for the server to signal that it started
			serverStartedEvent.WaitOne();
			
			Process procClient = Process.Start("PipeClient.exe");

			bool serverExit = procServer.WaitForExit(5000);
			bool clientExit = procClient.WaitForExit(5000);
			
			Assert.IsTrue(serverExit && clientExit);
		}

		[DeploymentItem(@"UnitTest\RemoteTest\RemoteTest.exe")]
		[TestMethod]
		public void TestRemoteEnvironment() 
		{
			Process proc = null;
			
			proc = Process.Start("RemoteTest.exe");

			// Inject once, and set a nothing variable
			RemoteEnvironment env = new RemoteEnvironment(proc.Id);

            env.SetEnvironmentVariable("CR_UTILITY_IGNORE", "ignored");
            env.SetEnvironmentVariable("A", "1");
            
            // Check that the variable was set
            string var = env.GetEnvironmentVariable("CR_UTILITY_IGNORE");

            Assert.AreEqual(var, "ignored");

            var = env.GetEnvironmentVariable("A");
            Assert.AreEqual(var, "1");

            ParsedPath path = new ParsedPath(Environment.CurrentDirectory, PathType.Directory);
            
            path = new ParsedPath(path.All).MakeParentPath();

            env.CurrentDirectory = path.All;
            
            string dir = env.CurrentDirectory;
            
            Assert.AreEqual(path.RootAndDirectoryNoSeparator, dir);
            
            env.Dispose();

			// Inject again and set the stop variable
			env = new RemoteEnvironment(proc.Id);

			env.SetEnvironmentVariable("CR_UTILITY_REMOTE_TEST", "stop");
			env.Dispose();
			
			proc.WaitForExit();
		}
	}
}
